package com.koron.css2.contractmanage.util;

import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Locale;

/**
 * 合同文件上传校验工具类
 *
 * @author 李文浩
 * @version YH230315
 * @date 2023/4/19 10:22
 */
public class FileUploadVerify {

    /**
     * 文件后缀 支持的类型
     */
    private static final String[] FILE_SUFFIX_SUPPORT = {".doc", ".docx", ".pdf", ".jpg", ".jpeg", ".png"};

    /**
     * 文件名字 需要排除的字符
     */
    private static final String[] FILE_NAME_EXCLUDE = {
            "`", "!", "@", "#", "$", "%", "^", "&", "*", "-", "=", "_", "+",
            "~", "·", "！", "￥", "……", "——", "?", ",", ":", ";", "/", "\\",
            "|", "？", "，", "。", "：", "；", "、"
    };

    /**
     * 文件大小 50MB
     */
    private static final long FILE_SIZE = 50 * 1024 * 1024;

    /**
     * 文件名后缀 .
     */
    private static final String POINT = ".";

    /**
     * 上传文件校验大小、名字、后缀
     *
     * @param multipartFile
     */
    public static void uploadVerify(MultipartFile multipartFile) {
        // 校验文件是否为空
        if (multipartFile == null) {
            throw new RuntimeException("上传文件不能为空！");
        }

        // 校验文件大小
        long size = multipartFile.getSize();
        if (size > FILE_SIZE) {
            throw new RuntimeException("上传文件大小不能超过10MB！");
        }

        // 校验文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        if (originalFilename == null) {
            throw new RuntimeException("上传文件名字不能为空！");
        }
        boolean nameFlag = false;
        for (String s : FILE_NAME_EXCLUDE) {
            if (originalFilename.contains(s)) {
                nameFlag = true;
                break;
            }
        }
        if (nameFlag) {
            throw new RuntimeException("上传文件名字不允许出现" + Arrays.toString(FILE_NAME_EXCLUDE) + "关键字！");
        }

        // 校验文件后缀
        if (!originalFilename.contains(POINT)) {
            throw new RuntimeException("上传文件不能没有后缀！");
        }
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        boolean flag = true;
        for (String s : FILE_SUFFIX_SUPPORT) {
            if (s.equals(suffix.toLowerCase(Locale.ROOT))) {
                flag = false;
                break;
            }
        }
        if (flag) {
            throw new RuntimeException("上传文件格式仅限于" + Arrays.toString(FILE_SUFFIX_SUPPORT) + "！");
        }
    }
}